package initialize

import (
	"fmt"
	"github.com/casbin/casbin/v2"
	gormadapter "github.com/casbin/gorm-adapter/v3"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

func NewCasbinAdapter(account, password, host, database string) *casbin.Enforcer {
	// 连接数据库
	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", account, password, host, database)
	adapter, err := gormadapter.NewAdapter("mysql", dsn, true)
	if err != nil {
		logx.Error(errors.Wrapf(err, "casbin NewAdapter error"))
		return nil
	}

	defer adapter.Close() //避免本地调试过多未能关闭连接以致服务器数据库连接数量过多无法连接数据库

	enforce, err := casbin.NewEnforcer("config/casbin.conf", adapter)
	if err != nil {
		logx.Error(errors.Wrapf(err, "casbin NewEnforcer error"))
		return nil
	}

	//LoadPolicy放在初始化那里会使如果修改了数据库中的权限需要重启服务才能刷新鉴权，可以放在鉴权的rpc里
	if err := enforce.LoadPolicy(); err != nil {
		logx.Error(errors.Wrapf(err, "casbin LoadPolicy error"))
		return nil
	}

	return enforce
}
